<template>
    <div>
        <div class="searchArea">
            <el-input v-model="taskName" placeholder="任务名称" class="searchTextInput" clearable/>
            <el-input v-model="groupId" placeholder="分组名" class="searchTextInput" clearable/>
            <el-button type="primary" class="searchButton" @click="loadData">查询</el-button>
            <div class="addTaskArea">
                <el-button type="primary" class="searchButton" @click="isShowCreateRPATaskDialog = true" plain>新增</el-button>
            </div>
        </div>
        <div class="searchArea">
            <el-form-item>
                <el-tag
                    v-for="tag in tagIds"
                    :key="tag"
                    class="mx-1 filterTag"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                >
                    {{ tag }}
                </el-tag>
                <el-input
                    v-if="inputVisible"
                    ref="InputRef"
                    v-model="inputValue"
                    class="tagInput"
                    size="small"
                    @keyup.enter="handleInputConfirm"
                    @blur="handleInputConfirm"
                />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
                    <el-icon size="10" color="black" style="margin-right:5px;">
                        <Filter />
                    </el-icon>
                     添加标签
                </el-button>
            </el-form-item>
        </div>
        <div class="table">
            <el-table 
            :data="tableData" 
            style="width: 100%" 
            max-height="500"
            stripe 
            border 
            :cell-style="{textAlign:'center'}"
            :header-cell-style="{textAlign:'center'}"
            >
                <el-table-column prop="id" label="ID" width="50" />
                <!-- <el-table-column prop="taskID" label="任务ID" width="88" /> -->
                <el-table-column prop="taskName" label="任务名称" width="88"/>
                <el-table-column prop="groupID" label="分组名" width="88" :formatter="formatGroupName"/>
                <el-table-column prop="tagIDs" label="标签" width="100" :formatter="getTagName">
                    <template #default="scope">
                        <div v-if="scope.row.tagIDs == ''">/</div>
                        <div v-else>
                            <el-tag class="tag" v-for="item in scope.row.tagIDs.split(',')" v-bind:key="item">{{ getTagName(item) }}</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="createAccount" label="创建人" width="88"/>
                <el-table-column prop="createTime" label="创建时间" width="155" :formatter="formatTime"/>
                <el-table-column prop="costPoint" label="消耗点数" width="88"/>
                <el-table-column prop="mark" label="备注" width="88"/>
                <el-table-column prop="morder" label="排序" width="88"/>
                <el-table-column fixed="right" label="操作" min-width="160">
                    <template #default="scope">
                        <el-button link type="success" size="small" @click="execute(scope.row)"
                        >执行</el-button>
                        <el-button link type="primary" size="small" class="editButton" @click="handleClickEdit(scope.row)"
                        >编辑</el-button>
                        <el-button link type="primary" size="small" class="editFlow" @click="handleClickEditFlow(scope.row)"
                        >编辑流程</el-button>
                        <el-button link type="primary" size="small" @click="handleClickDel(scope.row)" style="margin-left:0px;"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50, 100, 150, 200, 250, 300]"
                :small="false"
                :disabled="false"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="loadData"
                @current-change="loadData"
                total-text="总共"
                style="justify-content:end"
            />
        </div>
        <CreateRPATaskDialog v-if="isShowCreateRPATaskDialog" v-model:isShow="isShowCreateRPATaskDialog" :handleUpdated="loadData"></CreateRPATaskDialog>
        <EditRPATaskDialog v-if="isShowEditRPATaskDialog" v-model:isShow="isShowEditRPATaskDialog" :handleUpdated="loadData" v-model:data="selectedData"></EditRPATaskDialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted,reactive, computed,watch,nextTick} from 'vue'
import {useRouter, useRoute} from 'vue-router';
import RPAApi from '../../../apis/rpa';
import EnvApi from '../../../apis/env';
import { ElMessage, ElMessageBox, ElInput} from 'element-plus'
import CreateRPATaskDialog from './CreateRPATaskDialog.vue';
import EditRPATaskDialog from './EditRPATaskDialog.vue';
import { Filter } from '@element-plus/icons-vue'
import {formatTime} from '../../../utils/TimeUtils';

const isShowCreateRPATaskDialog = ref(false);
const isShowEditRPATaskDialog = ref(false);
var tableData:any = ref([])
const currentPage = ref(0)
const pageSize = ref(10)
const total = ref(200)
const taskName = ref("")
const groupId = ref("")
const selectedData = ref({});

const tagIds = ref<Array<string>>([]);
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const router = useRouter();
const route = useRoute();

console.log('[RPATaskMgr]Route', route.path);

let tags:any = [];
let groups:any = [];

const loadData = ()=>{
    RPAApi.fetchRPATag("", 0, 999).then(ret=>{
        if(ret.code == 0){
            tags = ret.data.list;
        }
        return RPAApi.fetchRPAGroup("", 0, 999);
    }).then(ret=>{
        if(ret.code == 0){
            groups = ret.data.list;
        }
        return RPAApi.fetchTasks(taskName.value, groupId.value, tagIds.value,currentPage.value, pageSize.value);
    }).then(ret=>{
        console.log('[RPATaskMgr]', ret);
        tableData.value = ret.data.list;
        total.value = ret.data.totalCount;
        currentPage.value = ret.data.page;
        pageSize.value = ret.data.pageSize;
    }).catch(err=>{
        console.log('[TenantList]', err);
    })
}

onMounted(()=>{
    console.log('[RPATaskMgr] onMounted');
    loadData();
})

const handleClickEdit = (row:any)=>{
    console.log('编辑', row);
    selectedData.value = row;
    isShowEditRPATaskDialog.value = true;
}

const handleClickEditFlow = (row:any)=>{
    console.log('编辑', row);
    router.push('/rpa/task/flow/'+row.id);
}

const handleClickDel = (row:any) => {
    console.log('删除', row);
    // 二次确认
    ElMessageBox.confirm(`确认删除租户${row.taskName}吗?`,'温馨提示',
        {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        }
    ).then(() => {
        let id = row.id;
        return RPAApi.delTask(id);
    }).then(ret=>{
        loadData();
        ElMessage({
            type: 'success',
            message: "删除成功",
        })
    }).catch((err) => {
        if(err=="cancel"){
            ElMessage({
                type: 'info',
                message: "取消删除操作",
            })
        }else{
            ElMessage({
                type: 'error',
                message: "删除失败",
            })
        }
    })

}

const handleClose = (tag: string) => {
  tagIds.value.splice(tagIds.value.indexOf(tag), 1)
  loadData();
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    tagIds.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
  loadData();
}

const getTagName = (tagID:any)=>{
    let filterTags = tags.filter((item:any)=>item.tagID == tagID);
    if(filterTags && filterTags.length>0){
        return filterTags[0].tagName;
    }else{
        return "未知标签";
    }
}

const formatGroupName = (row:any, column:any, cellValue:any, index:any)=>{
    let filterGroup = groups.filter((item:any)=>item.groupID == cellValue);
    if(filterGroup && filterGroup.length>0){
        return filterGroup[0].groupName;
    }else{
        return "未知分组";
    }
}

const execute = async (row:any)=>{
    console.log('ipcRenderer', (window as any).ipcRenderer);
    try {
        let reqData:{ action: string; data: string; envData?: string } = {"action":"executeTask", "data":JSON.stringify(row)};
        const taskDataCells = JSON.parse(row.taskData).cells;
        console.log('taskDataCells', taskDataCells);
        const filterCells = taskDataCells.filter((item:any)=> item.shape != 'edge' && item.data.id == "StartNode" );
        console.log('filterCells', filterCells);
        if(filterCells && filterCells.length>0) {
            const properties = filterCells[0].data.properties;
            const envID = properties[1].items[0].val;
            console.log('envID', envID, properties);
            RPAApi.executeTask(row.id, row.costPoint).then(ret=>{
                return EnvApi.fetchEnvByEnvID(envID);
            }).then(ret=>{
                if(ret.code == 0){
                    reqData["envData"] = JSON.stringify(ret.data);
                    (window as any).ipcRenderer.send('execute_rpa', reqData);
                }else{
                    ElMessage({
                        type:"error",
                        "message": "获取环境信息失败"
                    })
                }
            }).catch(err=>{
                ElMessage({
                        type:"error",
                        "message": err
                    })
                console.warn("[RPATaskMgr]执行流程失败", err);
            })
        }else{
            // 执行前 先扣除点数
            RPAApi.executeTask(row.id, row.costPoint).then(ret=>{
                if(ret.code == 0){
                    (window as any).ipcRenderer.send('execute_rpa', reqData);
                }else{
                    ElMessage({
                        type:"error",
                        "message": ret.message
                    })
                }                
            }).catch(err=>{
                ElMessage({
                        type:"error",
                        "message": err
                    })
            })
        }

        
        
        // EnvApi.fetchEnvByEnvID()
        
    } catch (error) {
        console.warn("[RPATaskMgr]未运行在Electron项目中。", error);
    }
}

</script>

<style scoped>
.pagination {
    margin-top: 15px;
}
.searchArea, .oeprations {
    padding-bottom: 10px;
    display: flex;
}
.searchButton {
    margin-left: 0px;
}
.searchTextInput {
    width: 120px;
    margin-right: 10px;
}
.operationButton {
    margin-right: 0px;
}
.filterTag {
    margin-right: 5px;
}
.tagInput {
    width: 100px;
}

.addTaskArea {
    display: inline-flex;
    position: absolute;
    right: 20px;
}
.editFlow, .editButton {
    margin-left: 0px;
}

.tag {
    margin-top: 5px;
}
</style>
